from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from userapp.models import *
import jsonpickle


# Create your views here.


def helloworld(request):
    return HttpResponse("hello world!!!!")


class Index(View):
    def get(self, request):
        """
            个人主页（分用户），暂时定为展示页面，需要登录授权才可访问
        """
        username = request.session.get('user')
        if username:
            return render(request, 'user/index.html')
        else:
            return redirect("userapp:login")

    def post(self, request):
        """
            暂定
        """
        pass


class Login(View):
    def get(self, request):
        return render(request, 'user/login.html')

    def post(self, request):
        """
            登录功能，获取request中用户名与密码与数据库比对，登录成功返回cookie并跳转主页
        """
        uname = request.POST.get("userid", "")
        pwd = request.POST.get("password", "")
        try:
            user = User.objects.get(username=uname, password=pwd)
            request.session['user'] = jsonpickle.dumps(user)
            return redirect("userapp:index")
        except User.DoesNotExist:
            msg = {"error": "用户名或密码错误"}
            # request.session['msg'] = "用户名或密码错误"
            # return redirect("userapp:login", msg="用户名或密码错误")
            return render(request, 'user/login.html', context=msg)


class Register(View):
    def get(self, request):
        return render(request, 'user/register.html')

    def post(self, request):
        """
            注册功能
        """
        uname = request.POST.get("username", "")
        password = request.POST.get("password", "")
        try:
            user = User.objects.get(username=uname, password=password)
            return render(request, 'user/register.html')
        except User.DoesNotExist:
            user = User.objects.create(username=uname, password=password)
            request.session['user'] = jsonpickle.dumps(user)

        return redirect("userapp:index")


class LoginOut(View):
    def get(self, request):
        request.session.flush()
        # return JsonResponse({"loginout": True})
        return redirect("userapp:login")
